package yxy.game.pm2.command.stairway;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.module.rank.RankWorship;
import yxy.game.pm2.bean.module.rank.RankWorshipPlayer;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.StairwayMessage;
import yxy.game.pm2.module.player.PlayerHandle;
import yxy.game.pm2.module.stairway.RankStairwayKing;

import java.util.Collection;

/** 天梯争雄 天梯王者 */
@MessageType(proto = Command.StairwayTop, classtype = StairwayMessage.StairwayTopRequest.class)
public class CMD_StairwayTop extends Command<StairwayMessage.StairwayTopRequest> {

	@Override
	public void execute(MessageSource messageSource, StairwayMessage.StairwayTopRequest request) {
		String playerCode = messageSource.getTag();

		StairwayMessage.StairwayTopResponse.Builder response = StairwayMessage.StairwayTopResponse.newBuilder();

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		RankStairwayKing rankStairway = new RankStairwayKing(areaBean.getGroupId());
		try {
			PlayerHandle playerHandle = new PlayerHandle();
			Collection<RankEntry> top = rankStairway.top(3);

			RankWorship worship = rankStairway.getWorship();
			RankWorshipPlayer worshipPlayer = RankWorshipPlayer.get(playerCode, worship);

			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();

				StairwayMessage.StairwayRank.Builder builder = StairwayMessage.StairwayRank.newBuilder();

				builder.setRank(++rank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(pCode));
				builder.setFans(worship.getScore(pCode));
				builder.setLiked(worshipPlayer.getWorshiped().contains(pCode));
				response.addShow(builder);
			}
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}

	}

	private void send(MessageSource messageSource, StairwayMessage.StairwayTopResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}